<template>
  <div class="BatchAddReport">
    <el-dialog
      :title="batchAdd.title"
      :visible.sync="batchAdd.open"
      width="1450px"
      append-to-body
      :close-on-click-modal="false"
      center
    >
      <!-- <div style="display: flex;padding-left: 130px;">
        <el-switch
          v-model="isMore"
          @change="typeChange()"
          active-color="#13ce66"
          active-text="一号多人"
          inactive-text="一号一人"
        >
        </el-switch>
      </div> -->
      <el-form
        :inline="true"
        :model="batchForm"
        ref="batchForm"
        label-width="100px"
        :rules="roleRules"
      >
        <div class="tit">
          <h2>医院信息</h2>
        </div>
        <el-row>
          <el-form-item label="医院名称" prop="hospitalId" width="50%">
            <el-select
              size="small"
              v-model="batchForm.hospitalId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择医院"
              @change="hospitalChange"
            >
              <el-option
                v-for="item in hospitalList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="科室名称" prop="officeId">
            <el-select
              size="small"
              v-model="batchForm.officeId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择科室"
              @change="officeChange"
            >
              <el-option
                v-for="item in pickOfficeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <!-- <a href="javascript:void(0);" @click="addOffice" style="margin-left: 230px">快速创建</a> -->
          </el-form-item>

          <el-form-item label="医生名称" prop="doctorId">
            <el-select
              size="small"
              v-model="batchForm.doctorId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择医生"
            >
              <el-option
                v-for="item in pickDoctorList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <!-- <a href="javascript:void(0);" @click="addDoctor" style="margin-left: 230px">快速创建</a> -->
          </el-form-item>

          <el-form-item label="医院项目" prop="hospitalItemIdList" v-if="itemShow">
            <el-select
              v-model="batchForm.hospitalItemIdList"
              filterable
              clearable
              size="small"
              reserve-keyword
              multiple
              :loading="loadingIns"
              placeholder="请选择医院项目"
              @change="hospitalItemChange"
            >
              <el-option
                v-for="item in pickHospitalItemList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="医检项目
          " prop="insItemIdList" v-if="!itemShow">
            <el-select
              v-model="batchForm.insItemIdList"
              filterable
              multiple
              placeholder="请选择医检项目"
              @change="itemListChange"
            >
              <el-option
                v-for="item in itemNameList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目名称" prop="itemName">
            <el-input size="small" v-model.trim="batchForm.itemName" :disabled="isForbidItemName"></el-input>
          </el-form-item>
        </el-row>
        <div class="tit" v-if="userRole === 1">
          <h2>医检机构</h2>
        </div>
        <el-row v-if="userRole === 1">
          <el-form-item label="医检名称" prop="institutionId">
            <el-select
              v-model="batchForm.institutionId"
              size="small"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择医检机构"
              @focus="listInstitutions"
              @change="institutionChange"
            >
              <el-option
                v-for="item in pickInstitutionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="科室名称" prop="insOfficeId">
            <el-select
              v-model="batchForm.insOfficeId"
              size="small"
              filterable
              clearable
              reserve-keyword
              placeholder="请选择科室"
            >
              <el-option
                v-for="item in pickInsOfficeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- <el-form-item
            label="医检条码号"
            v-if="isMore == true"
            prop="insReportCode"
          >
            <el-input
              v-model="batchForm.insReportCode"
              size="small"
              @blur="checkInsCodeIsExist"
            >
            </el-input>
            <br /><span
              id="insCodeHides"
              :hidden="insCodeHide"
              style="color: red; font-size: xx-small;"
            >
              <i class="el-icon-warning" />医检条码号重复！</span
            >
          </el-form-item> -->


        </el-row>
        <div class="tit">
          <h2>基础信息</h2>
        </div>
        <el-row>
           <el-form-item label="一级收样员" prop="syUserId">
            <el-select
              v-model="batchForm.syUserId"
              size="small"
              filterable
              clearable
              reserve-keyword
              placeholder="请选择一级收样员"
            >
              <el-option
                v-for="item in pickSyUserList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item id="groupSyUser" label="二级收样员" prop="syUserIdTwo">
            <el-select
              style="width: 85%;"
              v-model="batchForm.syUserIdTwo"
              size="small"
              filterable
              clearable
              reserve-keyword
              placeholder="请选择二级收样员"
            >
              <el-option
                v-for="item in pickSyUserList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-button
              style="padding:7px;"
              @click="addSubclass()"
              icon="el-icon-plus"
              plain
              round
              type="success"
              size="mini"
            ></el-button>
          </el-form-item>
          <el-form-item
            prop="syUserIdList"
            id="groupSyUser"
            v-for="(item, index) in batchForm.syUserIdList"
            size="small"
            :label="changSyUserLabel(index + 3)"
            :key="'syUserIdList' + index"
          >
            <el-select
              style="width: 85%;"
              v-model.lazy="item.userId"
              filterable
              clearable
              reserve-keyword
              placeholder="请选择收样员"
            >
              <el-option
                v-for="item in pickSyUserList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-button
              style="padding:7px;"
              @click="deleteSubclass(index)"
              icon="el-icon-close"
              plain
              round
              type="danger"
              size="mini"
            ></el-button>
          </el-form-item>
          <!-- <el-form-item label="查询号" prop="searchCode">
          <el-input size="small" v-model="batchForm.searchCode"></el-input>
        </el-form-item> -->
          <el-form-item label="送检时间" prop="reportBeginTime">
            <el-date-picker
              v-model="batchForm.reportBeginTime"
              type="datetime"
              size="small"
              :picker-options="pickerBeginDateBefore"
              :default-value="timeDefaultShow"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="不填则默认为当前时间"
            ></el-date-picker>
          </el-form-item>
          <!-- <el-form-item
            label="编号"
            v-if="isMore == true"
            prop="myReportCode"
          >
            <el-input size="small" v-model="batchForm.myReportCode"></el-input>
          </el-form-item> -->
          <el-form-item label="报告状态" prop="reportState">
            <el-select
              v-model="batchForm.reportState"
              size="small"
              clearable
              reserve-keyword
              placeholder="请选择当前报告状态"
            >
              <el-option
                v-for="item in pickCurReportStateList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="项目样本" prop="sampleTypeList">
          <el-select
            v-model="batchForm.sampleTypeList"
            size="small" style="width: 200px;"
            filterable
            clearable
            reserve-keyword
            multiple
            placeholder="请选择项目样本">
            <el-option
              v-for="item in pickSampleTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item> -->
          <el-form-item label="开启结果提醒" prop="isRemind">
            <el-switch
              v-model="batchForm.isRemind"
              active-color="#13ce66"
              size="small"
              active-value="1"
              inactive-value="0"
            ></el-switch>
          </el-form-item>
        </el-row>
        <div class="tit" style="display: flex;align-items: center;">
          <h2>用户信息</h2>
          <div>
            <el-button
              icon="el-icon-plus"
              type="success"
              plain
              size="medium"
              :disabled="batchFormDisabled"
              @click="AddTables"
              circle
            ></el-button>
          </div>
        </div>
        <el-table
          :data="batchForm.patientInformation"
          style="padding-left: 10px;"
        >
          <el-table-column label="操作" width="60">
            <template slot-scope="scope">

              <el-button
                icon="el-icon-plus"
                type="success"
                plain
                size="medium"
                :disabled="batchFormDisabled"
                @click="AddTables"
                circle
              ></el-button>

              <el-button
                icon="el-icon-minus"
                type="danger"
                plain
                size="medium"
                @click="DeleteTables(scope.$index)"
                circle
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
          ></el-table-column>
          <el-table-column label="姓名-必填" width="100">
            <template slot-scope="scope">
              <!-- @input="scope.row.patientName = scope.row.patientName.replace(/[^\u4E00-\u9FA5]/g, '')" -->
              <el-input
                size="mini"
                type="String"
                v-model.trim="scope.row.patientName"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            property="patientSex"
            label="性别"
            width="120"
            align="center"
          >
            <template slot-scope="scope">
              <!-- <el-switch
              v-model="scope.row.patientSex"
              active-color="#13ce66"
              active-value= "2" active-text="女"
              inactive-value= "1" inactive-text="男"></el-switch> -->
              <el-select v-model="scope.row.patientSex" size="mini">
                <el-option
                  v-for="item in listSex"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="身份证" width="200">
            <template slot-scope="scope">
              <el-input
                size="mini"
                @change="cardChange"
                maxlength="18"
                v-model.trim="scope.row.patientCard"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="出生日期" width="160">
            <template slot-scope="scope">
              <el-date-picker
              style="width:150px"
                size="mini"
                v-model="scope.row.birthday"
                type="date"
                placeholder="选择出生日期"
                value-format="yyyy-MM-dd"
                @change="getAgeByBirthday(scope.row.birthday,scope.$index)">
            </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="年龄" width="70">
            <template slot-scope="scope">
              <el-input
                size="mini"
                maxlength="3"
                v-model.trim="scope.row.patientAge"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="手机号" width="140">
            <template slot-scope="scope">
              <el-input
                size="mini"
                maxlength="11"
                @change="phoneChange"
                v-model.number="scope.row.patientPhone"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="医检条码号"
            v-if="isMore == false"
            width="160"
          >
            <template slot-scope="scope">
              <el-input
                size="mini"
                v-model.trim="scope.row.insReportCode"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="平台条码号"
            v-if="isMore == false"
            width="160"
          >
            <template slot-scope="scope">
              <el-input size="mini" v-model.trim="scope.row.myReportCode"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="180">
            <template slot-scope="scope">
              <el-input size="mini" v-model.trim="scope.row.remark"></el-input>
            </template>
          </el-table-column>
        </el-table>
        <!-- :disabled="batchFormDisabled" -->
        <el-form-item id="footBtn">
          <el-button
            type="primary"
            plain
            @click="sureReportClick"
            class="sureBtn"
            >保 存</el-button
          >
          <el-button @click="returnList">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <sameReportCheck
      ref="sameReportCheck"
      :dataList="sameReportList"
      @addReportSure="addReportSure"
    ></sameReportCheck>
  </div>
</template>

<script>
import SameReportCheck from "@/components/SameReportCheck";
import AuthApi from "@/api/system/auth";
import HospitalApi from "@/api/institution/hospital";
import InstitutionApi from "@/api/institution/institution";
import HospitalItemApi from "@/api/institution/hospitalItem";
import OfficeApi from "@/api/institution/office";
import DoctorApi from "@/api/institution/doctor";
import ReportApi from "@/api/report/report";
import InstitutionItemApi from "@/api/institution/institutionItem";

export default {
  name: "BatchAddReport",
  data() {
    return {
      pickCurReportStateList: [
        { label: "已收取", value: 5 },
        { label: "已送达", value: 10 }
      ],
      batchAdd: {
        // 批量新增
        open: false, // 默认隐藏
        title: ""
      },
      roleRules: {
        // 新增校验
        hospitalId: [
          {
            required: true,
            message: "请选择医院名称",
            trigger: "blur"
          }
        ],
        itemName: [
          {
            required: true,
            message: "请选择或输入送检项目",
            trigger: "blur"
          }
        ]
      },
      userRole: "",
      isMore: false, // 默认为一号一人
      insCodeHide: true,
      loadingIns: false,
      isForbidItemName:false, //是否禁用项目名称
      listSex: [
        { value: 1, label: "男" },
        { value: 2, label: "女" },
        { value: "", label: "未选择" }
      ],
      batchForm: {
        // 批量新增 - 表单内容
        hospitalId: "",
        officeId: "",
        doctorId: "",
        hospitalItemIdList:[],//医院组合项目id
        institutionId: "",
        insOfficeId: "",
        insReportCode: "",
        reportState: "",
        syUserId: "",
        syUserIdTwo: "", //二级收样员
        syUserIdList: [], // 三级及其后续收样员
        reportBeginTime: "",
        reportImageList: [],
        isRemind: "0",
        myReportCode: "",
        searchCode: "",
        itemName: "",
        patientInformation: [], // 患者信息
        insItemIdList: [] // 项目组
      },
      itemNameList: [], // 项目组列表
      itemShow: true, // 项目组的影藏以及显示
      pickerBeginDateBefore: {
        disabledDate(time) {
          // return time.getTime() < Date.now();
        }
      },
      batchFormDisabled: false,
      timeDefaultShow: "",
      // 全部的科室 医生 机构 列表
      pickOfficeList: [],
      pickDoctorList: [],
      pickInsOfficeList: [],
      pickInstitutionList: [],
      pickSampleTypeList: [], // 不同机构 对应的 样本项目列表
      pickSyUserList: [],
      hospitalList: [],
      pickHospitalItemList:[], //医院项目组列表
      sameReportList: [] // 相同平台/医检条码号的旧报告单列表
    };
  },
  components: {
    SameReportCheck
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.listSyUser();
      this.listHospital();
    },
    handleCreate() {
      // 父组件调用子组件
      this.batchAdd.open = true; // 显示弹出框
      this.batchAdd.title = "批 量 新 增";
      this.$Utils.clearData(this.batchForm);
      this.timeDefaultShow = new Date();
      this.typeChange();
      this.isForbidItemName = false
    },
    // 通过出生日期计算出年龄
    getAgeByBirthday(birthday,index){
      if(birthday){
        birthday = birthday.split('-')
        let date = new Date()
        let today = [date.getFullYear(),date.getMonth()+1,date.getDate()];
        let age = today.map((val,index)=>{
          return val - birthday[index]
        })
        if(age[2]<0){
          let lastMonth = new Date(today[0],today[1],0)
          age[1]--
          age[2]+=lastMonth.getDate()
        }
        if(age[1]<0){
          age[0]--
          age[1]+=12
        }
        this.batchForm.patientInformation[index].patientAge = age[0]
      }else{
        this.batchForm.patientInformation[index].patientAge = ""
      }
    },
    typeChange() {
      // 整体类型发生改变
      this.batchForm.patientInformation = [];
      // var type = this.isMore;
      //console.log(type);
      // if (type == true) {
      //   // 一号多人
      //   var cond = {
      //     patientName: "",
      //     patientSex: "",
      //     patientCard: "",
      //     patientAge: "",
      //     patientPhone: "",
      //     remark: ""
      //   };
      //   this.batchForm.patientInformation.push(cond);
      // } else if (type == false) {
        // 一号一人
        var otherCond = {
          patientName: "",
          patientSex: "",
          patientCard: "",
          birthday:"",
          patientAge: "",
          patientPhone: "",
          insReportCode: "",
          myReportCode: "",
          remark: ""
        };
        this.batchForm.patientInformation.push(otherCond);
      // }
    },
    // 非空时 校验身份证以及电话 错误就提示 但是不影响保存
    cardChange(val) {
      if (!this.$Utils.isEmptyObject(val)) {
        if (!this.$Utils.isCardNo(val)) {
          this.$Utils.messageError("身份证格式错误");
        }
      }
    },
    phoneChange(val) {
      if (!this.$Utils.isEmptyObject(val)) {
        if (!this.$Utils.isMobile(val)) {
          this.$Utils.messageError("电话号码格式错误");
        }
      }
    },
    getUserRole(val) {
      this.userRole = val;
    },
    listHospital() {
      let _this = this;
      _this.loadingIns = true;
      let cond = {
        hospitalType: 1
      };
      HospitalApi.getHospitalNameList(cond).then(res => {
        setTimeout(() => {
          _this.loadingIns = false;
          _this.hospitalList = res.data.map(item => {
            return {
              value: item.hospitalId,
              label: item.hospitalName
            };
          });
        }, 200);
      });
    },
    hospitalChange() {
      // 医院发生更变 - 加载科室
      let _this = this;
       // 清空其他选项数据
      _this.pickOfficeList = [];
      _this.batchForm.officeId = "";
      _this.pickDoctorList = [];
      _this.batchForm.doctorId = "";
      _this.pickInstitutionList = [];
      _this.batchForm.institutionId = "";
      _this.pickHospitalItemList = [];
      _this.batchForm.hospitalItemIdList = [];
      _this.batchForm.syUserId = "";
      _this.batchForm.itemName = ""
      _this.batchForm.insItemIdList = [];
      _this.itemNameList = []
      _this.itemShow = true;
      _this.isForbidItemName = false
      if (
        _this.batchForm.hospitalId == "" ||
        _this.batchForm.hospitalId == null
      ) {
        this.$message.error("请先选择医院");
        return;
      }


      let cond = {
        hospitalId: this.batchForm.hospitalId
      };
      OfficeApi.getOfficeNames(cond).then(res => {
        setTimeout(() => {
          _this.pickOfficeList = res.data.map(item => {
            return {
              value: item.officeId,
              label: item.officeName
            };
          });
        }, 200);
      });

      // 获取医院组合项目列表
      HospitalItemApi.listHospitalItemsName(cond).then(res=>{
        setTimeout(() => {
          _this.pickHospitalItemList = res.data.map(item => {
            return {
              value: item.itemId,
              label: item.itemName
            };
          });
        }, 200);
      })
    },
    officeChange() {
      // 科室信息发生更变 - 加载科室
      let _this = this;
      if (
        _this.batchForm.hospitalId == "" ||
        _this.batchForm.hospitalId == null
      ) {
        this.$message.error("请先选择医院");
        return;
      }
      if (_this.batchForm.officeId == "" || _this.batchForm.officeId == null) {
        this.$message.error("请先选择科室");
        return;
      }
      _this.pickDoctorList = [];
      _this.batchForm.doctorId = "";
      let cond = {
        hospitalId: _this.batchForm.hospitalId,
        officeId: _this.batchForm.officeId
      };
      DoctorApi.getDoctorNames(cond).then(res => {
        setTimeout(() => {
          _this.pickDoctorList = res.data.map(item => {
            return {
              value: item.doctorId,
              label: item.doctorName
            };
          });
        }, 200);
      });
    },
     // 医院项目改变
    hospitalItemChange(listId){
        this.pickInstitutionList = [];
        this.batchForm.institutionId = "";
        this.batchForm.itemName = ""
        this.itemShow = true;
        let arr = []

        if(listId.length>0){
          this.pickHospitalItemList.forEach(item=>{
            if(listId.some(id=>item.value==id)){
              arr.push(item.label)
            }
          })
          this.batchForm.itemName = arr.join(",")
          this.isForbidItemName = true
        }else{
           this.isForbidItemName = false
        }
    },
    listInstitutions() {
      // 当input获得焦点时触发
      // 根据医院id 获取匹配的机构
      let _this = this;
      if (!_this.batchForm.hospitalId) {
        this.pickInstitutionList = [];
        this.$message.error("请选择对应医院");
        return;
      }
      _this.loadingIns = true;
      if (_this.batchForm.hospitalItemIdList.length>0) {
        let cond = {
         hosItemIds: this.batchForm.hospitalItemIdList+''
        };
        InstitutionApi.listInsByHosItemId(cond)
          .then(res => {
            setTimeout(() => {
              _this.loadingIns = false;
              _this.pickInstitutionList  = res.data.map(item => {
                return {
                  value: item.institutionId,
                  label: item.institutionName
                };
              });
            }, 200);
          })
          .catch(error => {
            _this.pickInstitutionList = [];
            console.error(error);
          });
      }else{
        let cond = {
          hospitalId: _this.batchForm.hospitalId
        };
        InstitutionApi.getInsByHos(cond)
          .then(res => {
            setTimeout(() => {
              _this.loadingIns = false;
              _this.pickInstitutionList = res.data.map(item => {
                return {
                  value: item.institutionId,
                  label: item.institutionName
                };
              });
            }, 200);
          })
          .catch(error => {
            _this.pickInstitutionList = [];
            console.error(error);
          });
        }

    },
    institutionChange() {
      // 选中、改变 机构选项
      let _this = this;
      _this.pickInsOfficeList = [];
      _this.batchForm.insOfficeId = "";
      let cond = {
        institutionId: _this.batchForm.institutionId
      };
      // 获取机构列表
      OfficeApi.getOfficeNames(cond).then(res => {
        setTimeout(() => {
          _this.pickInsOfficeList = res.data.map(item => {
            return {
              value: item.officeId,
              label: item.officeName
            };
          });
        }, 200);
      });

      // 医检id为97/100 代表重庆医检机构
      if(this.batchForm.institutionId == 97 || _this.batchForm.institutionId == 100 || _this.batchForm.institutionId ==112|| _this.batchForm.institutionId == 124){

          InstitutionItemApi.getInstitutionItemList(cond)
          .then(res => {
            setTimeout(() =>{
              this.itemNameList = res.data.map(item => {
                return {
                  value: item.id,
                  label: item.name
                }
              })
            },200)
          })
          .catch(error => {
            _this.itemNameList = []
            console.error(error)
          })
            this.itemShow = false
            // 把项目名称隐藏
            this.isForbidItemName = false
            _this.batchForm.insItemIdList = []
             _this.batchForm.itemName = ""
          // 当医院项目大于0的时候，这个时候选择了重庆机构那么就重新开始选择
           if(_this.batchForm.hospitalItemIdList.length>0){
               _this.batchForm.hospitalId = "";

               _this.batchForm.hospitalItemIdList = []
               _this.pickHospitalItemList = []



            }
        }else{
          _this.itemNameList = []
          this.itemShow = true
        }
      // 更具机构id 获取样本的code和名称
        InstitutionApi.insSampleTypes(cond)
            .then(res => {
                setTimeout(() => {
                _this.pickSampleTypeList = res.data.map(item => {
                    return {
                    value: item.insSampleCode,
                    label: item.insSampleName
                    }
                })
                }, 200)
            })
            .catch(error => {
                _this.pickSampleTypeList = []
                console.error(error)
            })
    },
    /**
     * 选定特定医检时 出现该项目列表
     */
    itemListChange(value) {
      let _this = this;
      if(value.length>0){
        this.isForbidItemName = true
      }else{
        this.isForbidItemName = false
      }
      // 首先遍历每一个value值 在用每一个value值去找对应的label
      if (value != undefined || value.length >= 0) {
        var newList = [];
        value.forEach(item => {
          let choseValue = item;
          var choseList = _this.itemNameList.find(item => {
            return item.value == choseValue;
          });
          newList.push(choseList.label);
        });
        _this.batchForm.itemName = newList.join("，");

        // 珠海可允许一个条码号绑定不同类型的项目，一个条码号可以扫多次
        if (_this.batchForm.institutionId == 112) {
          return;
        }

        // 筛选出相同科室的项目
        if (value.length == 0 || value.length == 1) {
          let cond = {
            institutionId: _this.batchForm.institutionId
          };
          if (value.length == 1) {
            cond.itemId = value[0];
          }
          InstitutionItemApi.listInsItemNameAndGroup(cond)
            .then(res => {
              setTimeout(() => {
                _this.itemNameList = res.data.map(item => {
                  return {
                    value: item.itemId,
                    label: item.itemName + "-" + item.itemGroup
                  };
                });
              }, 200);
            })
            .catch(error => {
              _this.itemNameList = [];
              console.error(error);
            });
        }
        _this.batchForm.hospitalItemIdList = []
      }
    },
    listSyUser() {
      // 获取收样员列表
      let _this = this;
      AuthApi.listAdminByRole({
        roleId: 4
      }).then(res => {
        setTimeout(() => {
          _this.pickSyUserList = res.data.map(item => {
            return {
              value: item.userId,
              label: item.userName
            };
          });
        }, 200);
      });
    },
    checkInsCodeIsExist() {
      // 校验医检条码号是否重复
      let _this = this;
      if (
        _this.batchForm.insReportCode !== "" &&
        _this.batchForm.insReportCode !== null
      ) {
        _this.insCodeHide = true;
        if (!_this.batchForm.institutionId) {
          this.$message.error("请选择医检机构");
          return;
        }
        let cond = {
          institutionId: _this.batchForm.institutionId,
          insReportCode: _this.batchForm.insReportCode
        };
        ReportApi.getReportCount(cond)
          .then(res => {
            if (res.data && res.data > 0) {
              _this.insCodeHide = false;
            }
          })
          .catch(error => {
            _this.insCodeHide = true;
            console.error(error);
          });
      }
    },
    AddTables() {
      //每新增一个用户 上一个用户的信息 校验 名字、身份证、电话 是否重复以及其合法性
      // 添加一列表格
      var num = this.batchForm.patientInformation.length;
      // if (this.isMore == true) {
      //   // 一号多人
      //   var msg = {
      //     patientName: "",
      //     patientSex: "",
      //     patientCard: "",
      //     patientAge: "",
      //     patientPhone: "",
      //     remark: ""
      //   };
      // } else if (this.isMore == false) {
        // 一号一人
        var msg = {
          patientName: "",
          patientSex: "",
          patientCard: "",
          birthday:"",
          patientAge: "",
          patientPhone: "",
          insReportCode: "",
          myReportCode: "",
          remark: ""
        };
      // }
      var last = this.batchForm.patientInformation[num - 1].patientName;
      if (last == "") {
        this.$message.info("请先输入表中的必填信息！");
        return;
      } else {
        this.batchForm.patientInformation.push(msg);
      }
      //console.log(this.batchForm.patientInformation[num-1]); // 上一个信息
    },
    DeleteTables(index) {
      // 删除最后一列
      var num = this.batchForm.patientInformation.length;
      if (num != 1) {
        // 删除指定列
        this.batchForm.patientInformation.splice(index, 1);
      } else {
        this.$message.error("至少保留一条用户信息！");
      }
    },
    // 次级收样员
    addSubclass() {
      if (!this.batchForm.syUserId) {
        this.$message.error("请选择一级收样员");
        return;
      }
      if (!this.batchForm.syUserIdTwo) {
        this.$message.error("请选择二级收样员");
        return;
      }
      let data = { userId: null };
      this.batchForm.syUserIdList.push(data);
    },
    // 删除次级收样员
    deleteSubclass(index) {
      this.batchForm.syUserIdList.splice(index, 1);
      //console.log(JSON.stringify(this.reportForm.syUserIdList),1111111111)
    },
    // 显示多级收样员label
    changSyUserLabel(index) {
      let result = this.$Utils.numberToChinese(index);
      return result + "级收样员";
    },
    sureReportClicks() {
      //console.log(this.batchForm);
      //console.log(this.batchForm.patientInformation);
      var userMsgList = this.batchForm.patientInformation;
      if (userMsgList.length == 1) {
        // this.addBeforeCheck();
        //console.log(userMsgList[0]);
        // 只有一个用户 就遍历二维数组 校验 名字、身份证、电话 是否重复以及其合法性
      }
    },
    // 提交前校验
    beforeSureCheck() {
      let _this = this;
      //debugger
      let userList = _this.batchForm.patientInformation;
      // 判断姓名字段是否为空字符串
      let regName = /^\s+$/
      // 判断是否年龄在1到200之间
      let regAge = /^([1-9]|[1-9]\d|1\d{2}|200)$/
      // 判断是一号多人 or 一号一人
      // if (_this.isMore) {
      //   try {
      //     userList.forEach(a => {
      //       if (_this.$Utils.isNullStrict(a.patientName)||regName.test(a.patientName)) {
      //         throw new Error("提交失败：姓名不能为空！");
      //       }
      //       if(a.patientAge && !regAge.test(a.patientAge)){
      //         throw new Error("提交失败：年龄在1到200之间！");
      //       }
      //     });
      //   } catch (e) {
      //     _this.$message.error(e.message);
      //     return false;
      //   }

      //   let code01 = _this.batchForm.insReportCode; //医检条码
      //   let code02 = _this.batchForm.myReportCode; //康来条码
      //   if (
      //     _this.$Utils.isNullStrict(code01) &&
      //     _this.$Utils.isNullStrict(code02)
      //   ) {
      //     _this.$message.error("提交失败：康来、医检条码号不能同时为空！");
      //     return false;
      //   }
      // } else {
        // 这里是一号一人
        try {
          userList.forEach(a => {
            if (_this.$Utils.isNullStrict(a.patientName)||regName.test(a.patientName)) {
              throw new Error("提交失败：姓名不能为空！");
            }
            if(a.patientAge && !regAge.test(a.patientAge)){
              throw new Error("提交失败：年龄在1到200之间！");
            }

            if (
              _this.$Utils.isNullStrict(a.myReportCode) &&
              _this.$Utils.isNullStrict(a.insReportCode)
            ) {
              throw new Error("提交失败：康来、医检条码号不能同时为空！");
            }
          });
        } catch (e) {
          _this.$message.error(e.message);
          return false;
        }
      // }

      let names = [];
      let idCards = [];
      let myReportCodes = [];
      let insReportCodes = [];
      userList.forEach(a => {
        names.push(a.patientName);
        if (!_this.$Utils.isNullStrict(a.patientCard)) {
          idCards.push(a.patientCard);
        }
        if (!_this.$Utils.isNullStrict(a.myReportCode)) {
          myReportCodes.push(a.myReportCode);
        }
        if (!_this.$Utils.isNullStrict(a.insReportCode)) {
          insReportCodes.push(a.insReportCode);
        }
      });

      let names2 = _this.$Utils.unique(names);
      if (names.length != names2.length) {
        _this.$message.error("提交失败：用户信息中存在相同【姓名】！");
        return false;
      }
      let idCards2 = _this.$Utils.unique(idCards);
      if (idCards.length != idCards2.length) {
        _this.$message.error("提交失败：用户信息中存在相同【身份证】！");
        return false;
      }

      // if (!_this.isMore) {
        // 一号一人：分别判断是否同名、同身份证、同编号、同医检条码号
        let myReportCodes2 = _this.$Utils.unique(myReportCodes);
        if (myReportCodes.length != myReportCodes2.length) {
          _this.$message.error("提交失败：用户信息中存在相同【平台条码号】！");
          return false;
        }
        let insReportCodes2 = _this.$Utils.unique(insReportCodes);
        if (insReportCodes.length != insReportCodes2.length) {
          _this.$message.error("提交失败：用户信息中存在相同【医检条码号】！");
          return false;
        }
      // }

      return true;
    },
    sureReportClick() {
      //console.log("value=",this.batchForm.patientInformation)
      let _this = this;
      // 先前端校验
      let rtn = _this.beforeSureCheck();
      if (!rtn) {
        return;
      }

      // 如果是广东祈福医院那么患者身份证或者性别、年龄、出生日期必须选择一个填写完整
      if(_this.batchForm.institutionId==124){
        let info = _this.batchForm.patientInformation
        for(var i=0;i<info.length;i++){
          if((!info[i].patientSex||!info[i].birthday||!info[i].patientAge)&&!info[i].patientCard){
            this.$message.error("请输入完整性别、年龄、出生日期或者输入身份证")
            return
          }
        }
      }
      // 如果是医检项目那么必须选择项目
      if(!this.itemShow){
          if(this.batchForm.insItemIdList.length<1){
            this.$message.error("请选择医检项目")
            return
          }
      }

      var cond = {
        isMore: _this.isMore,
        institutionId: _this.batchForm.institutionId,
        insReportCode: _this.batchForm.insReportCode,
        myReportCode: _this.batchForm.myReportCode,
        hospitalId: _this.batchForm.hospitalId,
        reportBatchUserInfoPoList: _this.batchForm.patientInformation
      };
      ReportApi.batchAddCheck(cond).then(res => {
        if (res.status == 0) {
          if (res.data && res.data.length > 0) {
            _this.sameReportList = res.data;
            _this.$refs.sameReportCheck.handleCreate();
          } else {
            _this.batchAddReport();
          }
          _this.batchAdd.open = false;
        } else {
          _this.$Utils.notifyError(res.msg);
        }
      });
    },
    addReportSure() {
      // 客服点击确定为一号多人，隐藏弹出层，提交数据
      this.$refs.sameReportCheck.handleCancel();
      this.batchAddReport();
    },
    batchAddReport() {
      // 保存新增
      let _this = this;
      var cond = {
        isMore: _this.isMore,
        institutionId: _this.batchForm.institutionId,
        hospitalId: _this.batchForm.hospitalId,
        officeId: _this.batchForm.officeId,
        doctorId: _this.batchForm.doctorId,
        hosItemIds:_this.batchForm.hospitalItemIdList,
        syUserId: _this.batchForm.syUserId,
        syUserIdTwo: _this.batchForm.syUserIdTwo,
        syUserIdList: _this.batchForm.syUserIdList,
        myReportCode: _this.batchForm.myReportCode,
        insReportCode: _this.batchForm.insReportCode,
        reportState: Number(_this.batchForm.reportState),
        reportBeginTime: _this.batchForm.reportBeginTime,
        remind: Number(_this.batchForm.isRemind),
        itemName: _this.batchForm.itemName,
        insItemIdList: _this.batchForm.insItemIdList,
        reportBatchUserInfoPoList: _this.batchForm.patientInformation
      };
      ReportApi.batchAddReport(cond).then(data => {
        _this.$Utils.notifySuccess();
        _this.$parent.init(); // 调用父组件 刷新页面
        _this.returnList();
      });
    },
    returnList() {
      // 取消
      this.isForbidItemName = false;
      this.batchAdd.open = false;
    }
  }
};
</script>
<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
<style scoper>
form .el-row {
  padding: 0 25px;
}
form .tit {
  padding-left: 20px;
}
#groupSyUser .el-form-item__content {
  width: 220px;
}
#footBtn {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
}
.sureBtn {
  margin-right: 131px;
  margin-top: 34px;
}
</style>
